#include "sd.h"
#include "fatfs.h"
#include "sdio.h"
#include "usart.h"

DWORD sector_size = 512; // SD卡的扇区大小为512字节

// 分配一个大小适当的工作缓冲区
#define WORK_BUF_SIZE 1024 // 假设工作缓冲区大小为1KB
BYTE work_buf[WORK_BUF_SIZE];

extern FATFS fs;						/* Fatfs结构体    */
extern FIL file;						/* 文件对象结构体 */
extern FRESULT f_res;                   /* 文件操作返回值 */
extern UINT WorkBuffer[1024];

extern UINT WorkBuffer[1024];
extern UINT fnum;                      /* 文件成功读写数量 */
extern BYTE ReadBuffer[1024];    /* 读缓冲区 */
extern BYTE WriteBuffer[1024];            /* 写缓冲区 */

void Check_FileSystem(void)
{
    f_res = f_mount(&fs, "0:", 1);
    if(f_res != FR_OK)
    {
        printf("Mounting error: %d\r\n", f_res);
        while(1);
    }

    // 检查文件系统是否存在
    if(f_res == FR_NO_FILESYSTEM)
    {
        printf("The SD card does not yet have a file system and is about to be formatted...\r\n");

        // 格式化文件系统
        f_res = f_mkfs("0:", FM_FAT32, sector_size, work_buf, WORK_BUF_SIZE);
        if(f_res == FR_OK)
        {
            printf("The SD card file system formatted successfully\r\n");
        }
        else
        {
            printf("Formatting failed\r\n");
            while(1);
        }
    }
    else if(f_res != FR_OK)
    {
        printf("Mounting error: %d\r\n", f_res);
        while(1);
    }
    else
    {
        printf("Mounting success!!!\r\n");
    }

    f_mount(NULL, "0:", 1); // 卸载文件系统
}

void Create_ini_file(void)
{
    f_res = f_mount(&fs, "0:", 1);
    if(f_res != FR_OK)
    {
        printf("Mounting error: %d\r\n", f_res);
        return; // 如果文件系统挂载失败，直接返回，不执行后续操作
    }
    // 创建Default文件夹
    if(f_stat("0:\\Default", NULL) != FR_OK)
    {
        if(f_mkdir("0:\\Default") != FR_OK)
        {
            printf("mkdir fail");
        }
    }
    // 不存在则创建INI文件
    if(f_stat("0:\\Default\\settings.ini", NULL) != FR_OK)
    {
        printf("3");
        if(f_open(&file, "0:\\Default\\settings.ini", FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)
        {
            printf("4");
            char data[100];
            strcpy(data, "[Settings]\r\n");
            strcat(data, "Parameter1 = Value1\r\n");
            strcat(data, "Parameter2 = Value2\r\n");

            UINT bytes_written;
            f_write(&file, data, strlen(data), &bytes_written);
            f_close(&file);
        }
    }
    else
    {
        printf("ini file exist\n\r");
        f_close(&file);
    }
    f_mount(NULL, "", 1); // 卸载文件系统
}


